<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/27
 * Time: 10:56
 */

namespace app\api\controller;
use think\Controller;
use think\Request;
use GatewayWorker\Lib\Gateway;
use think\Db;
class Chat extends WxLogin
{
    /*public function __construct(){


    }*/
    private static $result_data = array(
        'code' => '0',
        'msg' => 'Parameter error',
        'data' => []
    );



    //测试
    public function test(){
        $data = [
            'type'=>'new_msg',
            'msg'=>'tsetInfo',
        ];
        Gateway::sendToGroup('1555568053336478', json_encode($data,JSON_UNESCAPED_UNICODE));
    }

    //聊天页面

    /**
     *  uid：用户id
     *  scoreId：牌局标识码
     */
    public function index(){
        $get_data = input('get.');
        $get_data['uid'] = $this->uid;
        //检测uid
        if($get_data['uid']){
            $user = Db::table('account_info')->where('uid',$get_data['uid'])->field('uid')->find();
            if(!$user){
                $rdata['msg'] = '用户不存在';
                echo json_encode($rdata,JSON_UNESCAPED_UNICODE);exit;
            }
        }

        //检测scoreId
        if($get_data['scoreId']){
            $score = Db::table('record_tabletotalscore')->where('ScoreID',$get_data['scoreId'])->field('ScoreID,GroupID')->find();
            if(!$score){
                $rdata['msg'] = '牌局不存在';
                echo json_encode($rdata,JSON_UNESCAPED_UNICODE);exit;
            }
        }else{
            $rdata['msg'] = '牌局ID为空';
            echo json_encode($rdata,JSON_UNESCAPED_UNICODE);exit;
        }


        $scoreId = $get_data['scoreId'];
        $uid = $get_data['uid'];
        $where = [];
        $where['r.ScoreID'] = $scoreId;
        //牌局内容
        $rData = Db::table('record_tabletotalscore')
            ->alias('r')
            ->where($where)
            ->join('(account_info a)','a.uid = r.Uid','LEFT')
            ->join('(gameinfo g)','g.KIND_ID = r.KindID','LEFT')
            ->field('r.*,a.NickName,a.FaceUrl,g.CHILD_GAME_NAME as ServiceName')
            ->order('r.TotalScore desc')
            ->select();
        foreach ($rData as $key=>$val){
            if($key == 0){
                $rData[$key]['WinUid'] = $val['Uid'];
            }else{
                $rData[$key]['WinUid'] = '';
            }
            $rData[$key]['face'] = base64_decode($val['FaceUrl']);
        }
        //聊天内容
        $chat_data = Db::table('tf_chat')
            ->alias('c')
            ->join('(account_info a)','a.uid = c.uid','LEFT')
            ->where('c.scoreId',$scoreId)
            ->field('c.*,a.NickName,a.FaceUrl')
            ->order('c.id')
            ->select();

        //用户表情包5张
        $bqWhere = [];
        $bqWhere['uid'] = $uid;
        $bqWhere['type'] = 2;
        $bqData = Db::table('tf_chat')->where($bqWhere)->order('id desc')->limit(4)->select();

        //牌局中是否存在群主
        $groupId = $score['GroupID'];
        $qzInfo = [];
        if($groupId){
            $qzId = Db::table('club_manager')->where('ClubID',$groupId)->field('CreateID,ClubName')->find();
            $qzInfo = Db::table('account_info')->where('uid',$qzId['CreateID'])->find();
            $qzInfo['ClubName'] = $qzId['ClubName'];
        }
        //dump($qzInfo);exit;
        $this->assign('data',$rData);
        $this->assign('qzInfo',$qzInfo);
        $this->assign('bqData',$bqData);
        $this->assign('chatData',$chat_data);
        $this->assign('uid',$uid);
        $this->assign('scoreId',$scoreId);
        $this->assign('is_sense',$this->is_sense);
        return $this->fetch();
    }

    /**
     * client_id绑定群组，群组为牌局ID
     */
    public function bind(){
        $post_data = input('post.');
        $client_id = $post_data['client_id'];
        $scoreId = $post_data['scoreId'];

        // 加入某个群组（可调用多次加入多个群组）
        Gateway::joinGroup($client_id, $scoreId);

    }

    /**
     * 上传名片信息
     */
    public function uploadCard(){
        if(Request::instance()->isPost()){

            $post_data = input('post.');

            if(empty($post_data['uid'])){
                self::$result_data['msg'] = 'uid required';
                return json_encode(self::$result_data);exit;
            }
            if(empty($post_data['scoreId'])){
                self::$result_data['msg'] = 'scoreId required';
                return json_encode(self::$result_data);exit;
            }

            //获取文件
            $file = request() -> file('img');
            // 验证图片,并移动图片到框架目录下。
            $info = $file -> validate(['ext' => 'jpg,png,jpeg','type' => 'image/jpeg,image/png']) -> move(ROOT_PATH.'public'.DS."uploads/cardImg");
            if($info){
                //保存图片至数据
                $img_path = "/public/uploads/cardImg/".$info->getSaveName();
                $insert_data = [
                    'photo_card'=>$img_path,
                ];
                $res_id = Db::table('account_info')->where('uid',$this->uid)->update($insert_data);
                if($res_id){
                    self::$result_data['msg'] = $insert_data;
                    self::$result_data['code'] = 200;
                }
            }else{
                // 文件上传失败后的错误信息
                $mes = $file->getError();
            }
            return json_encode(self::$result_data);
        }
    }

    /**
     * 获取名片信息
     */
    public function getPhotocard(){
        $uid = input('post.uid');
        if($uid){
            //获取账号信息
            $uInfo = Db::table('account_info')->where('uid',$uid)->field('FaceUrl,NickName,photo_card,uid')->find();
            if($uInfo){
                $uInfo['FaceUrl'] = base64_decode($uInfo['FaceUrl']);
                return json_encode($uInfo);
            }else{
                return '';
            }

        }
    }

    /**
     * 删除表情
     */
    public function delBq(){
        $post_data = input('post.');
        if(!empty($post_data['mesId'])){
            $res = Db::table('tf_chat')->where('id',$post_data['mesId'])->update(['type'=>1]);
        }
    }

    /**
     * 发送表情
     */
    public function sendBq(){
        $post_data = input('post.');
        if(!empty($post_data['mesId'])){
            //搜索表情内容
            $message = Db::table('tf_chat')->where('id',$post_data['mesId'])->field('message')->find();
            $insert_data = [
                'scoreId'=>$post_data['scoreId'],
                'uid'=>$post_data['uid'],
                'message'=>$message['message'],
                'send_time'=>date('Y-m-d H:i:s')
            ];
            $res = Db::table('tf_chat')->insert($insert_data);
            if($res){
                $data = [
                    'type'=>'new_msg',
                    'msg'=>$insert_data,
                ];
                Gateway::sendToGroup($post_data['scoreId'], json_encode($data,JSON_UNESCAPED_UNICODE));
            }
        }
    }

    /**
     * 发送消息
     */
    public function sendMsg(){
        $post_data = input('post.');
        $insert_data = [
            'scoreId'=>$post_data['scoreId'],
            'uid'=>$post_data['uid'],
            'message'=>$post_data['message'],
            'send_time'=>date('Y-m-d H:i:s')
        ];
        $res = Db::table('tf_chat')->insert($insert_data);
        if($res){
            $data = [
                'type'=>'new_msg',
                'msg'=>$insert_data,
            ];
            Gateway::sendToGroup($post_data['scoreId'], json_encode($data,JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 发送图片
     */
    public function sendPic(){
        if(Request::instance()->isPost()){

            $post_data = input('post.');


            if(empty($post_data['uid'])){
                self::$result_data['msg'] = 'uid required';
                return json_encode(self::$result_data);exit;
            }
            if(empty($post_data['scoreId'])){
                self::$result_data['msg'] = 'scoreId required';
                return json_encode(self::$result_data);exit;
            }

            //获取文件
            $file = request() -> file('img');
            // 验证图片,并移动图片到框架目录下。
            $info = $file -> validate(['ext' => 'jpg,png,jpeg','type' => 'image/jpeg,image/png']) -> move(ROOT_PATH.'public'.DS."uploads/chatImg");
            //dump($info->getSaveName());
            $limit4 = Db::table('tf_chat')->where('uid',$post_data['uid'])->where('type',2)->order('id desc')->limit(4)->select();
            if($info){
                //保存图片至数据
                $img_path = "<img src='/public/uploads/chatImg/".$info->getSaveName()."'>";
                $insert_data = [
                    'scoreId'=>$post_data['scoreId'],
                    'uid'=>$post_data['uid'],
                    'message'=>$img_path,
                    'type'=>2,
                    'send_time'=>date('Y-m-d H:i:s')
                ];
                $res_id = Db::table('tf_chat')->insertGetId($insert_data);
                if($res_id){
                    //更新用户最后一条图片类型为1
                    if(count($limit4) == 4){
                        $endData = end($limit4);
                        Db::table('tf_chat')->where('id',$endData['id'])->update(['type'=>1]);
                    }

                    $insert_data['id'] = $res_id;
                    self::$result_data['msg'] = $insert_data;
                    self::$result_data['code'] = 200;
                    $data = [
                        'type'=>'new_msg',
                        'msg'=>$insert_data,
                    ];
                    Gateway::sendToGroup($post_data['scoreId'], json_encode($data,JSON_UNESCAPED_UNICODE));
                }
            }else{
                // 文件上传失败后的错误信息
                $mes = $file->getError();
            }
            return json_encode(self::$result_data);
        }
    }

    /**
     * 创建文件夹
     */
    public function create_folder($file_name) {
        $dir = iconv("UTF-8", "GBK", "uploads/chatImg/".$file_name);//文件夹路径
        $path = ROOT_PATH.'public'.DS."uploads/chatImg/".$file_name;
        if (!file_exists($path)){
            mkdir ($path,0777,true);
            return $dir;
        } else {
            return $dir;
        }
    }

}